import { reactive, type Ref, ref, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import { getKeyList } from "@pureadmin/utils";
import { getSystemBackUp, deleteSystemBackup } from "@/api/systemcofig";
export function useBackup(tableRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const restreS = reactive({
    path: "",
    rsID: ""
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    searchText: ""
  });
  const selectedNum = ref(0);
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "编号",
      prop: "id"
    },
    {
      label: "备份描述",
      prop: "backName"
    },
    {
      label: "备份用户",
      prop: "backUser"
    },
    {
      label: "机构代码",
      prop: "comID"
    },
    {
      label: "备份日期",
      prop: "backDate"
    }
  ];
  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "backPath");

    tableRef.value.getTableRef().clearSelection();
    const Result = await deleteSystemBackup(frmIDS);
    if (Result.isSuccess) {
      message(`已删除编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const Result = await getSystemBackUp(pagination);
    dataList.value = Result.result;
    pagination.total = Result.onePage.total;
    pagination.pageSize = Result.onePage.pageSize;
    pagination.currentPage = Result.onePage.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }
  //分页选择
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    restreS.path = val[0].backName;
    restreS.rsID = val[0].id;
    console.log(restreS);
    //console.log("restreS.path", restreS.path);
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }
  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }
  onMounted(() => {
    onSearch();
  });
  return {
    form,
    selectedNum,
    loading,
    columns,
    dataList,
    pagination,
    resetForm,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel,
    restreS
  };
}
